package com.hhh.springai_test.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.constant.UserConstant;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.mapper.CommunityPostMapper;
import com.hhh.springai_test.model.dto.communityPost.AddCommunityPostDTO;
import com.hhh.springai_test.model.dto.communityPost.QueryCommunityPostDTO;
import com.hhh.springai_test.model.dto.communityPost.UpdateCommunityPostDTO;
import com.hhh.springai_test.model.enums.AuditStatusEnum;
import com.hhh.springai_test.model.po.CommunityCategory;
import com.hhh.springai_test.model.po.CommunityPost;
import com.hhh.springai_test.model.po.CommunityTag;
import com.hhh.springai_test.model.po.User;
import com.hhh.springai_test.service.CommunityCategoryService;
import com.hhh.springai_test.service.CommunityPostService;
import com.hhh.springai_test.service.CommunityTagService;
import com.hhh.springai_test.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author 29915
* @description 针对表【community_post(社区帖子表)】的数据库操作Service实现
* @createDate 2025-02-02 11:59:41
*/
@Service
public class CommunityPostServiceImpl extends ServiceImpl<CommunityPostMapper, CommunityPost>
    implements CommunityPostService {

    @Resource
    private UserService userService;

    @Resource
    private CommunityTagService communityTagService;

    @Resource
    private CommunityCategoryService communityCategoryService;


    @Override
    public long createPost(AddCommunityPostDTO addCommunityPostDTO) {
        // 获取当前登录用户的ID
        String loginUserId = (String) StpUtil.getLoginId();
        if (StrUtil.isEmpty(loginUserId)) {
            throw new BusinessException(ErrorCode.NO_LOGIN_CODE);
        }

        // 校验帖子标题是否已存在
        QueryWrapper<CommunityPost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", addCommunityPostDTO.getTitle());
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子标题已存在");
        }

        CommunityTag communityTagServiceById = communityTagService.getById(addCommunityPostDTO.getTagcode());
        if (communityTagServiceById == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子的tag标签不存在");
        }

        QueryWrapper<CommunityCategory> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("categorycode", addCommunityPostDTO.getCategorycode());
        long count1 = communityCategoryService.count(queryWrapper1);
        if (count1 <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子的category分类不存在");
        }

        CommunityPost communityPost = new CommunityPost();
        BeanUtil.copyProperties(addCommunityPostDTO, communityPost);

        // 设置默认值
        communityPost.setLikecount(0);
        communityPost.setCommentcount(0);
        communityPost.setViewcount(0);
        communityPost.setCreateuser(Long.parseLong(loginUserId));
        User user = userService.getById(Long.parseLong(loginUserId));
        if(user.getUserRole().equals(UserConstant.ADMIN_ROLE)){
            communityPost.setAuditstatus(AuditStatusEnum.APPROVED.getCode());
        }else{
            communityPost.setAuditstatus(AuditStatusEnum.PENDING.getCode());
        }
        // 保存帖子
        boolean success = this.save(communityPost);
        if (!success) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建帖子失败");
        }
        
        return communityPost.getId();
    }

    @Override
    public boolean updatePost(UpdateCommunityPostDTO updateCommunityPostDTO) {
        // 校验帖子是否存在
        CommunityPost oldPost = this.getById(updateCommunityPostDTO.getId());
        if (oldPost == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子不存在");
        }

        CommunityTag communityTagServiceById = communityTagService.getById(updateCommunityPostDTO.getTagcode());
        if (communityTagServiceById == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子的tag标签不存在");
        }

        QueryWrapper<CommunityCategory> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("categorycode", updateCommunityPostDTO.getCategorycode());
        long count1 = communityCategoryService.count(queryWrapper1);
        if (count1 <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子的category分类不存在");
        }

        // 获取当前登录用户的ID
        String loginUserId = (String) StpUtil.getLoginId();
        if (StrUtil.isEmpty(loginUserId)) {
            throw new BusinessException(ErrorCode.NO_LOGIN_CODE);
        }
        User user = userService.getById(Long.parseLong(loginUserId));
        // 检查是否是管理员
        if(!UserConstant.ADMIN_ROLE.equals(user.getUserRole())){
            // 不是管理员时检查是否是自己的帖子
            if(!user.getId().equals(oldPost.getCreateuser())){
                throw new BusinessException(ErrorCode.NOT_AUTH_CODE,"你没有权限修改该帖子数据");
            }
        }
        // 如果修改了标题，需要校验新标题是否已存在
        if (StrUtil.isNotBlank(updateCommunityPostDTO.getTitle()) 
            && !updateCommunityPostDTO.getTitle().equals(oldPost.getTitle())) {
            QueryWrapper<CommunityPost> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("title", updateCommunityPostDTO.getTitle());
            long count = this.count(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子标题已存在");
            }
        }
        CommunityPost updatePost = new CommunityPost();
        BeanUtil.copyProperties(updateCommunityPostDTO, updatePost);
        return this.updateById(updatePost);
    }

    @Override
    public Page<CommunityPost> queryPostPage(QueryCommunityPostDTO queryCommunityPostDTO) {
        QueryWrapper<CommunityPost> queryWrapper = new QueryWrapper<>();
        
        // 只查询已通过审核的帖子
        queryWrapper.eq("auditstatus", AuditStatusEnum.APPROVED.getCode());
        
        // 添加查询条件
        if (StrUtil.isNotBlank(queryCommunityPostDTO.getTitle())) {
            queryWrapper.like("title", queryCommunityPostDTO.getTitle());
        }
        // 只有当createuser大于0时才加入查询条件
        if (queryCommunityPostDTO.getCreateuser() != null && queryCommunityPostDTO.getCreateuser() > 0) {
            queryWrapper.eq("createuser", queryCommunityPostDTO.getCreateuser());
        }
        
        // 只有当传入分类代码时才进行分类验证和查询
        if (StrUtil.isNotBlank(queryCommunityPostDTO.getCategorycode())) {
            List<CommunityCategory> list = communityCategoryService.list();
            boolean categoryExists = false;
            for (CommunityCategory category : list) {
                if (queryCommunityPostDTO.getCategorycode().equals(category.getCategorycode())) {
                    categoryExists = true;
                    break;
                }
            }
            if (!categoryExists) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "帖子分类不存在");
            }
            // 添加分类查询条件
            queryWrapper.eq("categorycode", queryCommunityPostDTO.getCategorycode());
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc("createtime");
        queryWrapper.orderByAsc("tagcode");
        
        // 分页查询
        Page<CommunityPost> page = new Page<>(
            queryCommunityPostDTO.getCurrent(),
            queryCommunityPostDTO.getPageSize()
        );
        
        return this.page(page, queryWrapper);
    }

    @Override
    public Boolean HxxRemoveById(Long id) {
        CommunityPost communityPost = this.getById(id);
        if(communityPost == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"帖子不存在");
        }
        // 获取当前登录用户
        String loginUserId = (String) StpUtil.getLoginId();
        if (StrUtil.isEmpty(loginUserId)) {
            throw new BusinessException(ErrorCode.NO_LOGIN_CODE);
        }
        User currentUser = userService.getById(Long.parseLong(loginUserId));
        
        // 检查是否是管理员
        if(!UserConstant.ADMIN_ROLE.equals(currentUser.getUserRole())){
            // 不是管理员时检查是否是自己的帖子
            if(!currentUser.getId().equals(communityPost.getCreateuser())){
                throw new BusinessException(ErrorCode.NOT_AUTH_CODE,"你没有权限删除该帖子");
            }
        }
        return this.removeById(id);
    }
}